package com.hg.oa.widget;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CalendarView;

import com.hg.oa.R;
import com.hg.oa.util.DateUtil;

import java.util.Date;

/**
 * Created by fengxiang on 2016/9/13.
 */
public class CalendarViewDialog implements DialogInterface.OnClickListener {

    String tag = "CalendarViewDialog";

    AlertDialog dialog;
    OnDateSelectedListener listener;
    CalendarView calendarView;

    String selectedDate;

    public CalendarViewDialog(Context context, OnDateSelectedListener listener) {
        this.listener = listener;
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_select_date, null);
        calendarView = (CalendarView) view.findViewById(R.id.calendarView);
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setCancelable(true);
        builder.setView(view);
        builder.setPositiveButton(context.getString(R.string.dialog_btn_confirm), this);
        builder.setNegativeButton(context.getString(R.string.dialog_btn_cancel), this);
        dialog = builder.create();
        selectedDate = DateUtil.DateToString(new Date(), DateUtil.DateStyle.YYYY_MM_DD);
        calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
                selectedDate = year + "-" + (month + 1) + "-" + dayOfMonth;
            }
        });
    }

    public void show() {
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case DialogInterface.BUTTON_POSITIVE:
                Date date = DateUtil.StringToDate(selectedDate, DateUtil.DateStyle.YYYY_MM_DD);
                String dateStr = DateUtil.DateToString(date, DateUtil.DateStyle.YYYY_MM_DD);
                listener.onSelected(dateStr);
                break;
            case DialogInterface.BUTTON_NEGATIVE:
                dialog.dismiss();
                break;
        }
    }

    public interface OnDateSelectedListener {
        //date yyyy-MM-dd
        void onSelected(String date);
    }
}
